#include "stdafx.h"
#include "SoundM.h"
#include "RessourceManager.h"
#include "Jubox.h"

#pragma comment(lib, "User32.lib")

namespace GAMEPLAY
{
    Jubox::Jubox(void)
    {
    }

    Jubox::~Jubox()
    {
    }

    Jubox::Jubox(const std::wstring& szPath)
        :currentSongIndice_(0),music_(nullptr)
    {
        TCHAR szDir[MAX_PATH];
        HANDLE hFind = INVALID_HANDLE_VALUE;
        WIN32_FIND_DATA ffd;
        TCHAR path[MAX_PATH];

        std::copy(szPath.begin(),szPath.end(),path);
        path[szPath.size()] = 0;

        StringCchCopy(szDir, MAX_PATH,path);
        StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

        hFind = FindFirstFile(szDir, &ffd);
        FindNextFile(hFind, &ffd);
        FindNextFile(hFind, &ffd);

        do
        {
            std::wstring temp(szPath + L"\\");
            int i = 0;
            while(ffd.cFileName[i] != 0)
            {
                temp += ffd.cFileName[i++];
            }
            playList_.push_back(temp);
        }
        while (FindNextFile(hFind, &ffd) != 0);
    }

    void Jubox::operator ++()
    {
        currentSongIndice_ = (currentSongIndice_ + 1) %  playList_.size();
        if(music_)
        {
            stop();
            play();
        }
    }

    void Jubox::operator --()
    {
        if(currentSongIndice_ == 0)
            currentSongIndice_ = playList_.size() - 1;
        else
            --currentSongIndice_;

        if(music_)
        {
            stop();
            play();
        }
    }

    void Jubox::play()
    {
        if(!music_)
        {
            PM3D::RessourceManager<SoundM>& soundManager =
                PM3D::RessourceManager<SoundM>::getInstance();

            const int MAX_FILENAME = 256;

            char temp[MAX_FILENAME];
            std::wcstombs(temp, playList_[currentSongIndice_].c_str(), MAX_FILENAME - 1);
            std::string mbFilename(temp);

            music_ = soundManager.getNewRessource(mbFilename);

            music_->Play(true);
        }
    }

    void Jubox::stop()
    {
        if(music_)
        {
            music_->Stop();
        }
        music_ = nullptr;
    }

    std::wstring Jubox::getCurrentSongName() const
    {
        auto ittDebut = std::find(playList_[currentSongIndice_].begin(),playList_[currentSongIndice_].end(),'\\');

        ittDebut++;

        auto ittFin = std::find(playList_[currentSongIndice_].begin(),playList_[currentSongIndice_].end(),'.');

        return std::wstring(ittDebut,ittFin);
    }
}
